var $pageContainer = $("#pageContainer"),
    routerLogNum = 0;           //初次进入页面是0，以后每切换一次路由+1

var config = {
    enter: function (option) {
        routerLogNum++;
        var _path = option.current.matches;
        loadAssets(_path);
        console.log("enter: " + this.name + "; param: " + JSON.stringify(option.param))
    },
    leave: function (option) { console.log("leave: " + this.name + "; param: " + JSON.stringify(option.param)) },
    update: function (option) { console.log("update: " + this.name + "; param: " + JSON.stringify(option.param)) },
}

function cfg(o) {
    o.enter = o.enter || config.enter;
    o.leave = o.leave || config.leave;
    o.update = o.update || config.update;
    return o;
}

var router = {
    "home": config,
    "account.index": config,
    "account.banklist": config,
    "account.infofiles": config,
    "account.uploadDeposit": config,
    "account.pwdmodify": config,
    "deposit.index": config,
    "deposit.remit": config,
    "deposit.backlog": config,
    "extract.index": config,
    "extract.result": config,
    "extract.record": config,
    "transfer.index": config,
    // 交易报表
    "report.trade": config,
    "report.tradecode": config,
    "report.history": config,
    "report.settleOrder": config,
    
    "news.index": config,
    "page404": config,
    "app.contact": config,
    "app.contact.detail": cfg({ url: ":id(\\d+)" }),
    "app.contact.detail.setting": config,
    "app.contact.message": config,
    "app.user": cfg({
        enter: function (option) {
            var done = option.async();
            console.log(this.name + "is pending, 1s later to get into next state")
            setTimeout(done, 1000)
        },
        leave: function () {
            console.log(this.name + "is pending, 1s later to leave out")
            return new Promise(function (resolve) {
                setTimeout(resolve, 1000)
            })
        }
    }),
    "app.user.list": cfg({ url: "" })
};


// 动态加载资源文件
function loadAssets(_path) {
    $pageContainer.empty();
    // var load = layer.load(2, { shade: [.5, '#000'] });
    $pageContainer.append('<link rel="stylesheet" href="css' + _path + '.css">');
    Pace.start();
    $.when(
        $.ajax('views_'+_language + _path + '.html'),
        $.ajax('js_'+ _language + _path + '.js')
    ).then(function (html, js) {
        Pace.stop();
        // layer.close(load);
        $pageContainer.append(html[0]);
        avalon.scan($pageContainer[0]);

        const _title = $(html[0]).attr('data-title');
        document.title = _title || '客户中心';
        console.log('when', arguments);

        if( routerLogNum>1 ) setScrollTop();
    }, function (xhr, textStatus, errorThrown) {
        // layer.close(load);
        layer.alert('页面加载失败：'+_path + '<br />' + textStatus + '<br />' + errorThrown);
        console.log('catch', arguments);
    })
}

function setScrollTop(){

    var _top = $("#pageContainer").offset().top;
    $("html").animate({
        scrollTop:_top+'px'
    },300);
}

var stateman = window['stateman'] = new StateMan();
/* https://github.com/leeluolee/stateman */
stateman.state(router).on("notfound", function () {
     var goHash = '#'+stateman.state(location.hash=='' ? 'home' : 'page404').matches ;
     location.replace('//'+location.host+location.pathname+location.search + goHash)
}).start();
module.exports = stateman;